import * as icons from '@ant-design/icons'
import { Menu, type MenuProps } from 'antd'
import styles from './index.module.scss'
import { useLocation, useNavigate, useRouteLoaderData } from 'react-router-dom'
import useStore from '@/store'
import React, { useEffect, useState } from 'react'
import type { MenuItem } from '@/types/munuType'
type AntdMenuItem = Required<MenuProps>['items'][number]

const SideMenu = () => {
  const collapsed = useStore(state => state.collapsed)
  const data = useRouteLoaderData('layout')
  const [selectKeys, setSelectKeys] = useState<string[]>([])
  const [items, setItems] = useState<AntdMenuItem[]>([])
  const { pathname } = useLocation()
  const getItem = (
    label: React.ReactNode,
    key?: React.Key | null,
    icon?: React.ReactNode,
    children?: AntdMenuItem[]
  ): AntdMenuItem => {
    return {
      label,
      key,
      icon,
      children
    } as AntdMenuItem
  }
  const getIcon = (name?: string) => {
    if (!name) return <></>
    const customIcons: { [key: string]: any } = icons
    const icon = customIcons[name]
    if (!icon) return <></>
    return React.createElement(icon)
  }
  const getMenuTree = (menuList: MenuItem[], treeData: AntdMenuItem[] = []) => {
    menuList.forEach((item, index) => {
      if (item.menuType === 1 && item.menuState === 1) {
        if (item.buttons) {
          return treeData.push(getItem(item.menuName, item.path || index, getIcon(item.icon || '')))
        }
        treeData.push(
          getItem(item.menuName, item.path || index, getIcon(item.icon || ''), getMenuTree(item.children || []))
        )
      }
    })
    return treeData
  }
  const navigate = useNavigate()
  const handleLogo = () => {
    navigate('/welcome')
  }
  const handleClickMenu = ({ key }: { key: string }) => {
    navigate(key)
    setSelectKeys([key])
  }
  useEffect(() => {
    const res = getMenuTree(data.menuList)
    setItems(res)
    setSelectKeys([pathname])
  }, [])
  return (
    <div>
      <div className={styles.logo} onClick={handleLogo}>
        <img src='/imgs/logo.png' alt='' className={styles.img} />
        {!collapsed && <span>慕慕货运</span>}
      </div>
      <Menu
        selectedKeys={selectKeys}
        theme={'dark'}
        mode='inline'
        onClick={handleClickMenu}
        items={items}
        inlineCollapsed={collapsed}
      ></Menu>
    </div>
  )
}

export default SideMenu
